import arrow
from flask import Flask, request, g
from flask_migrate import Migrate
from config import DeConfig
from db_init import db
from view.user import user
from view.get_order import goods
from view2.oupon import oupon
from view.tast import test
from view2.user import userlist
from model.model import User_log

app = Flask(__name__)
app.config.from_object(DeConfig)
migrate = Migrate()
db.init_app(app)
migrate.init_app(app,db)

"""请求前中间件
    获取当前请求的url地址
    拿到这个用户的id
    orm 找到这个用户
    获取这个用户的所有角色
    获取这个用户的所有权限
    判定 当前请求地址 在不在这个些权限内
        不在就 返回 make_response('你没权限')
"""

# @app.before_request
# def check_power():
#     # 判断需要校验的接口
#     if str(request.url) in ['/user/register','/user/login']:
#         return None
#     # 获取传递用户的id
#     uid = request.args.get('uid') or g.get('uid')
#     if not uid:
#         return {'msg':'请传递用户id','code':408}
#     # 获取用户的信息
#     user = User.query.get(uid)
#     if not user:
#         return make_response({'msg':'没有这个用户','code':400})
#     # 获取用户的全部权限，组成一个列表
#     powers = sum([role.power for role in user.role_id], [])
#     # 拼接用户权限的请求方式，请求路由
#     items = [item.url + ':' + item.method for item in powers]
#     # 拼接传递的请求方式，请求路由
#     power_list = str(request.url_rule) + ':' + request.method.lower()
#     # 判断校验的请求 是否在权限里
#     if power_list not in items:
#         return make_response('没有这个权限')

# g是上下文管理工具
@app.after_request
def add_log(response):
    try:
        uid = request.args.get('u_id') or g.get('uid')
        if not uid:
            raise KeyError
    except Exception as e:
        print(request.url,e)
        return response
    log = User_log(user_id=uid,url=request.url,methods=request.method,create_time=arrow.get().int_timestamp)
    db.session.add(log)
    db.session.commit()
    return response

# if  DeConfig.PROJECTG_ENV == 'view':
#     app.register_blueprint(user)
#     app.register_blueprint(goods)
#     app.register_blueprint(oupon)
#     app.register_blueprint(test)
# elif DeConfig.PROJECTG_ENV == 'view2':
#     app.register_blueprint(userlist)

app.register_blueprint(userlist)
app.register_blueprint(user)
app.register_blueprint(goods)
app.register_blueprint(oupon)
app.register_blueprint(test)

if __name__ == '__main__':
    print(app.url_map)
    app.run(host='0.0.0.0',port=9327)


